# !/user/bin/env python
# coding=utf-8

from app_thread import *
from video import *
from urllib.request import urlretrieve
import zipfile
import os,sys, phpserialize
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
from baiducloud import *


def m(name):
    log_dir_path = os.getcwd() + '/Upload/Mixkit/'+name
    if os.path.exists(log_dir_path) != True:
        os.makedirs(log_dir_path)

    return log_dir_path

def getZipDir(dirpath, outFullName):
    """
    压缩指定文件夹
    :param dirpath: 目标文件夹路径
    :param outFullName: 压缩文件保存路径+xxxx.zip
    :return: 无
    """
    zip = zipfile.ZipFile(outFullName, "w", zipfile.ZIP_DEFLATED)
    for path, dirnames, filenames in os.walk(dirpath):
        # 去掉目标跟路径，只对目标文件夹下边的文件及文件夹进行压缩
        fpath = path.replace(dirpath, '')

        for filename in filenames:
            zip.write(os.path.join(path, filename), os.path.join(fpath, filename))
    zip.close()

def do_data(redis_obj, redis_obj_b, redis_obj_c, all_key,mod_val):
    for x in all_key:
        last_val = x.decode('utf8')[-1]
        if int(mod_val)!=int(last_val):
            continue
        data_json = redis_obj.get(x)
        data = json.loads(data_json)
        if redis_obj_b.exists(x) == 0:
            try:
                print(data['id'])
                tag_list = []
                for var in data['tag_list']:
                    if var:
                        tag_list.append(tran(var))
                print(tag_list)
                file_name = data['small_videl'].split('/')[-1].split('.')[0]

                file_name_ext = data['video_url'].split('/')[-1]
                if os.path.isfile('./img/' + file_name + '.jpg') != True:
                    urlretrieve(data['cover'], './img/' + file_name + '.jpg')

                if os.path.isfile('./mixkit_video/' + data['small_videl'].split('/')[-1]) != True:
                    download_mp4(data['small_videl'], 'E:/python/mixkitweb/mixkit_video/')

                dirname_path = m('video/' + data['id']) + '/'
                if os.path.isfile(dirname_path + file_name_ext) != True:
                    download_mp4(data['video_url'], dirname_path)

                share_url = ''
                pwd = ''
                if os.path.isfile(dirname_path + file_name_ext) == True:
                    if os.path.getsize(dirname_path + file_name_ext) >= 4 * 1024 * 1024:
                        os.system('split -b 4m ' + dirname_path + file_name_ext + ' ' + dirname_path + data['id'] + '_')
                        share_result = baidu_file(data['id'], 'video', dirname_path + file_name_ext, 1)
                    else:
                        share_result = baidu_file(data['id'], 'video', dirname_path + file_name_ext, 0)

                    share_url = share_result['shorturl']
                    pwd = share_result['pwd']

                # if os.path.isdir(zip_path_dir + '/video/' + data['id']) != True:
                #     files = [os.getcwd() + '/copy_dir/Pr小栈 – 这里有你想要的模板与插件.url', os.getcwd() + '/copy_dir/使用前必看.txt',
                #              os.getcwd() + '/copy_dir/成为会员 – Pr小栈.url']
                #     for f in files:
                #         shutil.copy(f, dirname_path)

                # getZipDir(dirname_path, zip_path_dir + '/video' + data['id'] + '.zip')

                detail = tran(data['detail']) if data['detail'] != None else ''
                qiniu_small_videl = 'https://file.prxz.vip/cover/small/2022-06-25/' + data['small_videl'].split('/')[-1]
                dic = {
                    'id': data['id'],
                    'cover': data['cover'],
                    'qiniu_cover': 'https://file.prxz.vip/cover/img/2022-06-25/' + file_name + '.jpg',
                    'small_videl': data['small_videl'],
                    'qiniu_small_videl': qiniu_small_videl,
                    'url': data['url'],
                    'detail': detail,
                    'description': tran(data['description']) if data['description'] != None else '',
                    'tag_list': ','.join(tag_list) if tag_list != [] else '',
                    'video_url': data['video_url'],
                    'share_url': share_url + '|tq=' + pwd,
                    'attr1': [{
                        'title': detail,
                        'view_url_id': 544,
                        'url': qiniu_small_videl
                    }],
                    'attr2': [{
                        'url': '点击下载|%s|tq=%s' % (share_url, pwd),
                        'attire': '插件|无需使用第三方插件 适用软件|全部 模板格式|.mp4 模板视频|不附带模板音乐',
                        'login': 'login lv0|credit=30 lv1|credit=20 lv2|credit=15 lv3|credit=10 lv4|credit=5 lv5|credit=1 vip|free'
                    }],
                }

                redis_obj_b.set(x, json.dumps(dic))

            except Exception as e:
                redis_obj_c.set(x, data_json)
                continue

if __name__ == '__main__':
    redis_obj = get_redis(1)
    redis_obj_b = get_redis(0)
    redis_obj_c = get_redis(2)
    all_key = redis_obj.keys('*')
    cate_url_list = []
    for i in range(0,10):
        # do_data(redis_obj,redis_obj_b,redis_obj_c,all_key,i)
        # exit()
        cate_url_list.append({'redis_obj': redis_obj,'redis_obj_b': redis_obj_b,'redis_obj_c': redis_obj_c,'all_key': all_key, 'mod_val': i})

    th_obj = MultiThreadTask(func=do_data, thread_num=len(cate_url_list), params_lst=cate_url_list)
    th_obj.start()